#include "echo_server.h"

#include "netlib/base/logger.h"
#include "netlib/net/socket/tcp_connection.h"

using namespace netlib;

EchoServer::EchoServer(netlib::net::EventLoop* loop, const netlib::net::InetAddress& addr) :
    loop_(loop), server_(loop, addr, "EchoServer") {
	server_.SetConnectionCallback(
	    [this](auto&& PH1) { onConnection(std::forward<decltype(PH1)>(PH1)); });
	server_.SetMessageCallback([this](auto&& PH1, auto&& PH2, auto&& PH3) {
		onMessage(std::forward<decltype(PH1)>(PH1), std::forward<decltype(PH2)>(PH2),
		          std::forward<decltype(PH3)>(PH3));
	});
}

void EchoServer::start() { server_.Start(); }

void EchoServer::onConnection(const netlib::net::TcpConnectionPtr& conn) {
	LOG_INFO << "EchoServer <-> " << conn->PeerAddress().ToIpPort() << " : "
	         << conn->LocalAddress().ToIpPort() << " is " << (conn->Connected() ? "UP" : "DOWN");
}

void EchoServer::onMessage(const netlib::net::TcpConnectionPtr& conn,
                           netlib::net::Buffer* buf,
                           netlib::Timestamp time) {
	std::string msg(buf->RetrieveAllAsString());
	LOG_INFO << conn->Name() << " echo " << msg.size() << "bytes, "
	         << "data received at " << time.ToString();
	conn->Send(msg);
}
